package com.baizhi.aop;

import com.baizhi.annolation.LogAnnotation;
import com.baizhi.entity.Admin;
import com.baizhi.entity.LogRecord;
import com.baizhi.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Date;
@Aspect
@Configuration
public class LogAop {
    @Autowired
    private LogService logService;

    //注解切割  去到定义有这个注解的注解上去进行增强处理
    @Pointcut("@annotation(com.baizhi.annolation.LogAnnotation)")
    public void logPoint(){}

    @After("logPoint()")
    public void logAfter(JoinPoint joinPoint){
        System.out.println("正在进入-------------------");
        //新建一个日志信息对象 之后赋值添加到数据库
        LogRecord logRecord = new LogRecord();

        //从当前线程中得到request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //从session作用域中取出用户对象
        HttpSession session=request.getSession();
        Admin admin = (Admin)session.getAttribute("admin");
if (admin!=null) {
    //获取请求地址的ip地址
    String remoteHost = request.getRemoteHost();

    //拿到签名
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    //拿到调用的方法
    Method method = signature.getMethod();
    //拿到方法上的注解
    Annotation annotation = method.getAnnotation(LogAnnotation.class);

    //拿到注解类的 属性值
    String type = ((LogAnnotation) annotation).type();
    String value = ((LogAnnotation) annotation).value();

    logRecord.setContent(value);
    logRecord.setDate(new Date());
    logRecord.setIp(remoteHost);
    logRecord.setName(admin.getUserName());
    logRecord.setType(type);
    System.out.println(
            logRecord
    );
    logService.insertLog(logRecord);

}





    }
}
